
import { reroute } from '../nav/reroute';
import { BOOTSTRAPPING, LOADING_SOURCE_CODE, NOT_MOUNTED,MOUNTED, NOT_BOOTSTRAPPED, NOT_LOADED,SKIP_BECAUSE_BROKEN,shouldBeActive} from './app.helpers'


/**
 * 加载应用
 * @param {*} appName  当前注册应用的名字
 * @param {*} loadApp 加载函数(必须返回的是promise)，返回的结果必须包含bootstrap、mount和 unmount做为接入协议
 * @param {*} activeWhen  满足条件时调用loadApp方法
 * @param {*} customProps 自定义属性可用于父子应用通信
 */
const apps = []; //存放所用的应用

export function registerApplication(appName,loadApp,activeWhen,customProps){ 
    // debugger
    apps.push({ //这里将应用注册好了
        name:appName,
        loadApp,
        activeWhen,
        customProps,
        status:NOT_LOADED // 默认应用为未加载
    });
    reroute() //加载应用
}


export function getAppChanges (){
    const appsToLoad = []; //要加载的app
    const appsToMount = []; //需要挂载的app
    const appsToUnmount = []; //要卸载的app

    
    apps.forEach((app)=>{
        // 需不需要被加载
        const appShouldBeActive = app.status !== SKIP_BECAUSE_BROKEN && shouldBeActive(app);
        switch(app.status){
            // 没有被加载
            case NOT_LOADED:
            case LOADING_SOURCE_CODE:
                if(appShouldBeActive){
                    appsToLoad.push(app);
                }
                break;
            // 需要被加载
            case NOT_BOOTSTRAPPED:
            case BOOTSTRAPPING:
            case NOT_MOUNTED:
                if(appShouldBeActive){
                    appsToMount.push(app);
                }
                break
            //需要被卸载
            case MOUNTED:
                if(!appShouldBeActive){
                    appsToUnmount.push(app);
                }
        }

    })
    return {
        appsToUnmount,
        appsToLoad,
        appsToMount
    }
    
}
